<template>
  <div>
    <div class="btn_box" style="margin: 20px 0">
      <el-form
        ref="searchForm"
        :inline="true"
        :model="search"
        style="margin-top: 20px"
      >
        <el-form-item prop="teacher">
          <el-input
            v-model="search.teacher"
            placeholder="根据教师查询"
            style="width: 200px"
          ></el-input>
        </el-form-item>
        <el-form-item prop="manager">
          <el-input
            v-model="search.manager"
            placeholder="根据学管查询"
            style="width: 200px"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="searchData">查询</el-button>
          <el-button type="danger" round @click="resetForm('searchForm')"
            >重置</el-button
          >
          <el-button type="primary"  icon="el-icon-thumb" @click="handleAdd">添加班级</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table :data="classs" height="380" border style="width: 100%">
      <el-table-column type="index" label="序号" width="60"> </el-table-column>
      <el-table-column prop="classname" label="班级名称"> </el-table-column>
      <el-table-column
        prop="teacher_id"
        label="教师名称"
        :formatter="formatTeacher"
      >
      </el-table-column>
      <el-table-column
        prop="manager_id"
        label="助教名称"
        :formatter="formatManger"
      >
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row._id)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="handleDele(scope.row._id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="currentPage"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
    <!-- 添加/编辑弹窗 -->
    <el-dialog title="班级编辑" :visible.sync="classFormVisible" width="500px">
      <el-form
        :model="updateclass"
        ref="classForm"
        label-width="100px"
        label-position="right"
        style="width: 400px"
        :rules="rules"
      >
        <el-form-item label="班级名称" prop="classname">
          <el-input
            v-model="updateclass.classname"
            placeholder="请输入班级名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="授课教师" prop="teacher_id">
          <el-select v-model="updateclass.teacher_id" placeholder="请点击选择">
            <el-option
              v-for="option in teacherOptions"
              :key="option._id"
              :label="option.name"
              :value="option._id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="助教" prop="manager_id">
          <el-select v-model="updateclass.manager_id" placeholder="请点击选择">
            <el-option
              v-for="option in managerOptions"
              :key="option._id"
              :label="option.name"
              :value="option._id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="classFormVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="
            updateclass._id == null
              ? addData('classForm')
              : updateData('classForm')
          "
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
 
 
 <script>
import { formateDate } from "@/utils/dateUtils.js";
import classApi from "@/api/class";
import userApi from "@/api/user";
export default {
  data() {
    return {
      teacherOptions: [],
      managerOptions: [],
      classFormVisible: false,
      currentPage: 1,
      totalPage: 1,
      pageSize: 5,
      total: 0,
      classs: [],
      updateclass: {
        _id: null,
        classname: "",
        teacher_id: "",
        manager_id: "",
      },
      search: {
        teacher: "",
        manager: "",
      },
      searchMap: {
        teacher_id: "",
        manager_id: "",
      },
      userAll: [],
      roleOptions: [],
      rules: {
        classname: [
          {
            required: true,
            message: "班级名称必须输入",
            trigger: ["blur", "change"],
          },
        ],
      },
    };
  },

  components: {},
  mounted() {
    this.fetchclass();
    this.getUserList();
  },
  methods: {
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.searchMap.teacher_id = "";
      this.searchMap.manager_id = "";
      this.fetchclass();
    },
    searchData() {
      this.currentPage = 1;
      const resTeacher =
        this.userAll.find((item) => item.name == this.search.teacher) || {};
      const resManager =
        this.userAll.find((item) => item.name == this.search.manager) || {};
      this.searchMap.teacher_id = resTeacher._id || "";
      this.searchMap.manager_id = resManager._id || "";
      console.log("1111",this.searchMap);
      this.fetchclass();
    },
    formatTeacher(row, column, cellValue, index) {
      const teacher = this.userAll.find((item) => item._id == cellValue) || {};
      return teacher.name;
    },
    formatManger(row, column, cellValue, index) {
      const manager = this.userAll.find((item) => item._id == cellValue) || {};
      return manager.name;
    },
    getUserList() {
      userApi.getUserAll().then((response) => {
        const res = response.data;
        if (res.status === 0) {
          this.userAll = res.data;
          this.userAll.forEach((item) => {
            if (item.role_id === "6322979ee6ce6366206d0aad") {
              this.teacherOptions.push(item);
            } else if (
              item.role_id === "632297a3e6ce6366206d0ab0"
            ) {
              this.managerOptions.push(item);
            }
          });
        }
      });
    },
    addData(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          classApi.add(this.updateclass).then((res) => {
            const resp = res.data;
            if (resp.status == 0) {
              this.$message({
                type: "success",
                message: "添加班级成功咯！",
              });
              this.classFormVisible = false;
              this.fetchclass();
            }
          });
        } else {
          return false;
        }
      });
    },
    updateData(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          classApi.update(this.updateclass).then((res) => {
            const resp = res.data;
            if (resp.status == 0) {
              this.$message({
                type: "success",
                message: "修改班级信息成功咯！",
              });
              this.classFormVisible = false;
              this.fetchclass();
            }
          });
        } else {
          return false;
        }
      });
    },
    handleAdd() {
      this.class = {
        _id: null,
        classname: "",
        teacher_id: "",
        manager_id: "",
      };
      this.classFormVisible = true;
      this.$nextTick(() => {
        this.$refs["classForm"].resetFields();
      });
    },
    fetchclass() {
      if (this.currentPage > Math.ceil(this.totalPage)) {
        this.currentPage = Math.ceil(this.totalPage);
      }
      classApi.getclassList(this.currentPage, this.pageSize,this.searchMap).then((res) => {
        const resp = res.data;
        if (resp.status == 0) {
          this.classs = resp.data.data;
          this.total = resp.data.total;
          this.totalPage = this.total / this.pageSize;
        }
      });
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.fetchclass();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.fetchclass();
    },
    reseDate(row, column, cellValue, index) {
      return formateDate(cellValue);
    },
    handleEdit(_id) {
      this.handleAdd();
      classApi.getByid(_id).then((res) => {
        const resp = res.data;
        console.log(resp.data);
        if (resp.status == 0) {
          this.updateclass = resp.data;
        }
      });
    },
    handleDele(id) {
      console.log("删除");
      this.$confirm("确认删除这条记录吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        classApi.deleteByid(id).then((res) => {
          const resp = res.data;
          console.log(resp.data);
          if (resp.status == 0) {
            this.$message({
              type: "success",
              message: "删除班级成功咯！",
            });
            this.totalPage = (this.total - 1) / this.pageSize;
            this.fetchclass();
          }
        });
      });
    },
    // formatRole(row, column, cellValue, index) {
    //   const role = this.roleOptions.find((item) => item.id === cellValue) || {};
    //   return role.name;
    // },
  },
};
</script>
 
 <style scoped>
</style>